package com.clps.digital.util;

import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.Executors;
import java.util.concurrent.ScheduledExecutorService;
import java.util.concurrent.TimeUnit;

/**
 * @author: Chase
 * @date: 2024/9/2 11:23
 * @Version: 1.0
 * @description:
 */

public class TokenCache {
    private final static ConcurrentHashMap<String, Long> map = new ConcurrentHashMap<>();

    private final static ScheduledExecutorService scheduler = Executors.newScheduledThreadPool(1);

    public static void put(String key, Long value, Long duration, TimeUnit timeUnit) {
        map.put(key, value);
        scheduleRemoval(key, duration, timeUnit);
    }

    public static Long get(String key) {
        return map.get(key);
    }

    public static void remove(String key) {
        map.remove(key);
    }

    private static void scheduleRemoval(String key, Long duration, TimeUnit timeUnit) {
        scheduler.schedule(() -> map.remove(key), duration, timeUnit);
    }

    public static void clear() {
        map.clear();
        scheduler.shutdownNow();
    }
}
